package com.douban.auth
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import org.iotashan.oauth.OAuthConsumer;
	import org.iotashan.oauth.OAuthRequest;
	import org.iotashan.oauth.OAuthSignatureMethod_HMAC_SHA1;
	import org.iotashan.oauth.OAuthToken;
	
	public class DBOAuth extends EventDispatcher
	{
		private static var DOUBAN_KEY : String = "01939220edcbfff404bab662c963ffdc";
		private static var DOUBAN_SECRET_KEY : String = "41e14b8e8fe1cec8 ";
		
		private static var DOUBAN_REQUEST_URL : String =
			"http://www.douban.com/service/auth/request_token";
		private static var DOUBAN_AUTHORIZE_URL : String =
			"http://www.douban.com/service/auth/authorize";
		private static var DOUBAN_ACCESS_TOKEN_URL : String =
			"http://www.douban.com/service/auth/access_token";
		
		private var httpGetRequestToken:HTTPService;
		private var httpGetAccessToken:HTTPService;
		
		private var oAuth_Token:String = '';
		private var oAuth_Token_Secret:String = '';
		
		public function DBOAuth()
		{
			super(null);
			httpGetRequestToken = new HTTPService();
			httpGetAccessToken.addEventListener(ResultEvent.RESULT,httpGetRequestTokenHandler);
			httpGetAccessToken = new HTTPService();
			httpGetAccessToken.addEventListener(ResultEvent.RESULT,httpGetAccessTokenHandler);
		}
		
		public function getRequestToken():void
		{
			httpGetRequestToken.url = generateRequestTokenURL();
			httpGetRequestToken.send();
		}
		
		/**
		 *  生成URL的辅助函数
		 *  当参数type:Object为：
		 *      NULL:       生成获取Request Token的URL
		 *      NOT NULL:   生成获取Access Token的URL  或者  生成访问受限资源时的URL
		 */
		private function  generateRequestTokenURL(type:Object = null):String
		{
			var oauth : OAuthRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_POST, null);
			oauth.consumer = new OAuthConsumer(DOUBAN_KEY, DOUBAN_SECRET_KEY);
			if (type == null)
			{
				oauth.requestURL = DOUBAN_REQUEST_URL;
			}
			else
			{
				oauth.requestURL = type.url;
				oauth.token = new OAuthToken(oAuth_Token, oAuth_Token_Secret);
			}
			return oauth.buildRequest(new OAuthSignatureMethod_HMAC_SHA1(), OAuthRequest.RESULT_TYPE_URL_STRING);
		}
		
		/**
		 *  step 2: step1发起请求后处理得到的Request Token和Request Token Secret，重定向到用户认证页面
		 */
		private function httpGetRequestTokenHandler(evt:ResultEvent):void
		{
			var urlRequest : URLRequest = new URLRequest();
			urlRequest.url = DOUBAN_AUTHORIZE_URL;
			urlRequest.data = handleTokens(evt);
			navigateToURL(urlRequest, '_blank');
			Alert.okLabel = '完成认证';
			Alert.show('请在打开的新页面中完成授权后，在这里点击完成认证', '提示', 4, null, getAccessToken);
		}
		
		/**
		 *  step 3: 用户在step2完成授权后，用generateRequestTokenURL()生成的URL发起请求，
		 *          得到Access Token和Access Token Secret
		 */
		private function getAccessToken(evt:CloseEvent):void
		{
			if (evt.detail == Alert.OK)
			{
				var type:Object = {url:DOUBAN_ACCESS_TOKEN_URL};
				httpGetAccessToken.url = generateRequestTokenURL(type);
				httpGetAccessToken.send();
			}
		}
		
		/**
		 *  辅助函数：对请求生成的URL后返回的token进行处理
		 */
		private function handleTokens(evt:ResultEvent):URLVariables
		{
			var res:String = evt.result as String;
			var params:URLVariables = new URLVariables();
			params.decode(res);
			oAuth_Token = params["oauth_token"];
			oAuth_Token_Secret = params["oauth_token_secret"];
			return params;
		}
		
		private function httpGetAccessTokenHandler(evt:ResultEvent):void
		{
			handleTokens(evt);
			//将Access Token和Access Token Secret存进数据库
//			this.btn.label = '已完成认证';
//			this.btn.enabled = false;
		}
	}
}